import json
import time

import traci


def vehicleInfo(veh_id):
    x, y = traci.vehicle.getPosition(veh_id)
    lon, lat = traci.simulation.convertGeo(x, y)
    speed = traci.vehicle.getSpeed(veh_id)
    accel = traci.vehicle.getAcceleration(veh_id)
    length = traci.vehicle.getLength(veh_id)
    width = traci.vehicle.getWidth(veh_id)
    height = traci.vehicle.getHeight(veh_id)
    angle = traci.vehicle.getAngle(veh_id)
    signals = traci.vehicle.getSignals(veh_id)
    veh_number = '鲁' + str(veh_id)
    ptcId = "-" + veh_number[3:]

    obj = {
        "id": veh_number,
        "lon": str(lon),
        "lat": str(lat),
        "speed": str(speed),
        "accel": str(accel),
        "length": str(length),
        "width": str(width),
        "height": str(height),
        "angle": str(angle),
        "signal": str(signals),
        "ptcId": str(ptcId),
        "timestamp": str(int(round((time.time()) * 1000)))
    }
    return obj


def personInfo():
    personIds = traci.person.getIDList()
    if len(personIds) == 0:
        return
    else:
        for personID in personIds:
            x, y = traci.person.getPosition(personID)
            lon, lat = traci.simulation.convertGeo(x, y)
            obj = {
                "id": personID,
                "speed": str(traci.person.getSpeed(personID)),
                "lon": str(lon),
                "lat": str(lat),
                "length": str(traci.person.getLength(personID)),
                "width": str(traci.person.getWidth(personID)),
                "height": str(traci.person.getHeight(personID)),
                "angle": str(traci.person.getAngle(personID)),
                "ptcId": str(personID),
                "timestamp": str(int(round((time.time()) * 1000)))
            }
            return obj


def sendRedis(idSet, conn_road, msg_key):
    person = personInfo()
    conn_road.lpush(msg_key, json.dumps(person))
    # 将车辆信息发往redis中
    ids = traci.vehicle.getIDList()
    for veh_id in ids:
        msg = vehicleInfo(veh_id)
        msg_key = msg_key
        conn_road.lpush(msg_key, json.dumps(msg))
    # 获取路网中出现的车，并放到set集合中
    for id in traci.simulation.getDepartedIDList():
        id = "FH-" + str(id)[2:]
        idSet.add(id)
    # 从set集合中移除路网中显示的车辆
    arrivedList = traci.simulation.getArrivedIDList()
    for veh in arrivedList:
        veh = "FH-" + str(veh)[2:]
        idSet.remove(veh)
    # 记录路网中的车辆是否在线状态
    list1 = list(idSet)
    for li in list1:
        conn_road.set(li, li)
        conn_road.expire(li, 1)